# -----------------------------------------------------------------------------
# calc.py
#
# A simple calculator with variables.   This is from O'Reilly's
# "Lex and Yacc", p. 63.
# -----------------------------------------------------------------------------

import ply.yacc as yacc

LexerDebug = True
tokens = (
    'NAME', 'NUMBER', 'ASSIGN',
    "GT", "LT", "GE", "LE", 'EQUAL', 'NOTEQUAL'
)

literals = ['+', '-', '*', '/', '(', ')', '^']

t_ASSIGN = r"="

t_GT = r">"
t_LT = r"<"
t_GE = r">="
t_LE = r"<="
t_NOTEQUAL = r"!="
t_EQUAL = r"=="
# Tokens

t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'  # 代表标识符的正则表达式。只能是单个字符，而且执行的优先级比其他标识符更加靠后。


def t_NUMBER(t):
    r'(\d+\.\d+|\d+)'  # 可以将其扩展到数字的正则表达式，以及浮点数。
    t.value = float(t.value)
    return t


t_ignore = " \t"


def t_newlin(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")


def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)


# Build the lexer
import ply.lex as lex

lex.lex()

# Parsing rules

precedence = (
    ('left', '+', '-'),
    ('left', '*', '/'),
    ("left", "EQUAL"),
    ("left", "NOTEQUAL"),
    ('right', 'UMINUS'),
)

# dictionary of names
names = {}


# def p_stateme_pow

def p_statement_assign(p):
    'statement : NAME ASSIGN expression'
    names[p[1]] = p[3]


def p_statement_expr(p):
    'statement : expression'
    print(p[1])


def p_expression_equal(p):  # 注意，函数定义中是按照顺序进行添加的！
    'expression : expression EQUAL expression'
    p[0] = (p[1] == p[3])


def p_expression_not_equal(p):
    """expression : expression NOTEQUAL expression
                |   expression GE expression
                |   expression GT expression
                |   expression LE expression
                |   expression LT expression
    """
    if p[2] == "!=":
        p[0] = not (p[1] == p[3])
    elif p[2] == ">=":
        p[0] = (p[1] >= p[3])
    elif p[2] == ">":
        p[0] = (p[1] > p[3])
    elif p[2] == "<=":
        p[0] = (p[1] <= p[3])
    elif p[2] == "<":
        p[0] = (p[1] < p[3])


def p_expression_binop(p):
    '''expression : expression '+' expression
                  | expression '-' expression
                  | expression '*' expression
                  | expression '/' expression
                  | expression '^' expression
                  '''
    if p[2] == '+':
        p[0] = p[1] + p[3]
    elif p[2] == '-':
        p[0] = p[1] - p[3]
    elif p[2] == '*':
        p[0] = p[1] * p[3]
    elif p[2] == '/':
        p[0] = p[1] / p[3]
    elif p[2] == '^':
        p[0] = p[1] ** p[3]


def p_expression_uminus(p):
    "expression : '-' expression %prec UMINUS"
    p[0] = -p[2]


def p_expression_group(p):
    "expression : '(' expression ')'"
    p[0] = p[2]


def p_expression_number(p):
    "expression : NUMBER"
    p[0] = p[1]


def p_expression_name(p):
    "expression : NAME"
    try:
        p[0] = names[p[1]]
    except LookupError:
        print("Undefined name '%s'" % p[1])
        p[0] = 0


def p_error(p):
    if p:
        print("Syntax error at '%s'" % p.value)
    else:
        print("Syntax error at EOF")


yacc.yacc()

while 1:
    try:
        s = input('calc > ')
    except EOFError:
        break
    if not s: continue
    yacc.parse(s)
